
// ignore_for_file: constant_identifier_names

import 'dart:math';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

enum ItemHighlightType { IS_TOP, IS_RECOMMEND, IS_CHOOSE }

class WordRichSimpleText extends StatefulWidget {
  final String? title;
  final int? maxTextSize;
  final TextStyle? textStyle;
  const WordRichSimpleText({
    Key? key,
    this.maxTextSize,
    this.title,
    this.textStyle,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _WordRichSimpleTextState();
  }
}

class _WordRichSimpleTextState extends State<WordRichSimpleText> {

  int get _maxSize => widget.maxTextSize ?? 112;
  bool get expandedEnable => (widget.title?.length ?? 0) > _maxSize;
  bool _expanded = false;

  TapGestureRecognizer? _expandTapGestureRecognizer;


  @override
  void initState() {
    super.initState();
    _expandTapGestureRecognizer = TapGestureRecognizer()
      ..onTapDown = _toggleExpanded;
  }

  @override
  void dispose() {
    _expandTapGestureRecognizer?.dispose();
    super.dispose();
  }

  String getSubString(String text, int start, int end) {
    if (end + 1 >= text.length) return text;
    if (end < text.runes.length) {
      String targetText =
          String.fromCharCodes(text.runes.toList().sublist(start, end));
      return targetText;
    }
    return text;
  }


  void _toggleExpanded(TapDownDetails detail) {
    _expanded = !_expanded;
    setState(() {});
  }


  @override
  Widget build(BuildContext context) {
    return Text.rich(
      TextSpan(
        style: widget.textStyle ??
            TextStyle(
              color: Colors.white.withOpacity(0.6),
              fontSize: 14,
              height: 1.4,
            ),
        children: [
          if (expandedEnable == false)
            _buildContentTextPan()
          else ...[
            _buildContentTextPan(),
            TextSpan(
              text: _expanded ? "" : "...",
              recognizer: _expandTapGestureRecognizer,
            ),
            TextSpan(
              text: _expanded ? "     收起" : " 全文",
              style: const TextStyle(
                color: Colors.white,
                fontSize: 14,
                height: 1.4,
              ),
              recognizer: _expandTapGestureRecognizer,
            ),
          ],
        ],
      ),
    );
  }

  TextSpan _buildContentTextPan() {
    if (expandedEnable) {
      return TextSpan(
        text: _expanded
            ? widget.title
            : getSubString(widget.title ?? "", 0, max(_maxSize, 0)).trim(),
      );
    } else {
      return TextSpan(
        text: widget.title,
      );
    }
  }
}
